package com.ciccwm.dubbo.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Dubbo日志过滤器
 */
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER})
public class DubboLogFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(DubboLogFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String side = RpcContext.getServiceContext().getUrl().getParameter(CommonConstants.SIDE_KEY);
        String serviceName = invoker.getInterface().getSimpleName();
        String methodName = invocation.getMethodName();
        Object[] args = invocation.getArguments();

        if (CommonConstants.PROVIDER_SIDE.equals(side)) {
            LOGGER.info("Provider received request - Service: {}, Method: {}, Args: {}", serviceName, methodName, args);
        } else {
            LOGGER.info("Consumer sending request - Service: {}, Method: {}, Args: {}", serviceName, methodName, args);
        }

        long startTime = System.currentTimeMillis();
        Result result = invoker.invoke(invocation);
        long endTime = System.currentTimeMillis();

        if (CommonConstants.PROVIDER_SIDE.equals(side)) {
            LOGGER.info("Provider sending response - Service: {}, Method: {}, Result: {}, Time: {}ms",
                    serviceName, methodName, result.getValue(), (endTime - startTime));
        } else {
            LOGGER.info("Consumer received response - Service: {}, Method: {}, Result: {}, Time: {}ms",
                    serviceName, methodName, result.getValue(), (endTime - startTime));
        }

        return result;
    }
} 
